package com.bojx.cms.service;

import java.util.List;

import com.bojx.cms.dao.QuestionDao;
import com.bojx.cms.dao.UserDao;
import com.bojx.cms.model.User;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;

public class QuestionService {
	private static QuestionDao questionDao = new QuestionDao();
	private static UserDao userDao=new UserDao();
	public long count(String keyword) {
		if (StrKit.isBlank(keyword)) {
			return questionDao.queryCount();
		} else {
			return questionDao.queryCount(keyword);
		}

	}

	public List<Record> queryQuestions(long pageNum, String keyword) {
		int start = (int) ((pageNum - 1) * 20);
		int end = (int) pageNum * 20 - 1;
		if (StrKit.isBlank(keyword)) {
			return questionDao.queryQuestions(start, end);
		} else {
			return questionDao.queryQuestions(start, end, keyword);
		}
	}

	public Record findQuestionInfo(long id) throws Exception {
		Record question = questionDao.queryQuestionById(id);
		if (question == null) {
			throw new Exception("没有这条记录");
		}
		long userId = question.getLong("user_id");
		String avatar = User.dao.findById(userId).getStr("avatar");
		question.set("avatar", avatar);
		return question;
	}

	public List<Record> findAnswersInfo(long id) {
		List<Record> result = questionDao.queryAnswersByQuesId(id);
		for(Record record:result){
			long userId = record.getLong("user_id");
			String avatar = User.dao.findById(userId).getStr("avatar");
			record.set("avatar", avatar);
		}
		return result;
	}
	
	public void saveAnswer(long questionId,String desc,String username){
		Record user=userDao.queryUserInfo(username);
		long userId=user.getLong("user_id");
		long departId=user.getLong("depart_id");
		String departName=user.getStr("depart_name");
		Record answerRecord=new Record();
		answerRecord.set("user_id", userId);
		answerRecord.set("depart_id", departId);
		answerRecord.set("user_name", username);
		answerRecord.set("depart_name", departName);
		answerRecord.set("question_id", questionId);
		answerRecord.set("desc", desc);
		questionDao.saveAnswer(answerRecord);
	}
}
